package com.stnet.dao.enterprice.chinamobile;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;

import com.modules.commons.Pager;
import com.stnet.bases.BaseDaoImpl;
import com.stnet.entity.OnlineRecharge;

/**
 * @author Messcat
 * @version 1.1
 * 
 */
public class OnlineRechargeDaoImpl extends BaseDaoImpl implements OnlineRechargeDao {

	public OnlineRechargeDaoImpl() {
	}

	public void delete(OnlineRecharge onlineRecharge) {
		getHibernateTemplate().delete(onlineRecharge);
	}

	public void delete(Long id) {
		getHibernateTemplate().delete(get(id));
	}

	public List findAll() {
		List find = getHibernateTemplate().find("from onlinerecharge");
		return find;
	}

	public void save(OnlineRecharge onlineRecharge) {
		try {
			getHibernateTemplate().save(onlineRecharge);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}

	public void update(OnlineRecharge onlineRecharge) {
		getHibernateTemplate().merge(onlineRecharge);
	}

	public OnlineRecharge get(Long id) {
		return (OnlineRecharge) getHibernateTemplate().get(OnlineRecharge.class, id);
	}
	
	public  OnlineRecharge getByOuttradeid(String outtradeid) {
		OnlineRecharge onlineRecharge = null;
		try {
			List find = getHibernateTemplate().find(
					"from OnlineRecharge where outtradeid = ? ", outtradeid);
			if(find.size() != 0){
				onlineRecharge = (OnlineRecharge) find.get(0);
			}
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return onlineRecharge;
	}

	public List findOnlineRechargeByAgent(Long agent) {
		List find = getHibernateTemplate().find(
				"from OnlineRecharge where user.id = ? order by id desc", agent);
		return find;

	}

	public Pager getListByAgent(int pageSize, int pageNo, Long agent) {
		Session session = null;
		Pager pager = null;

		session = getHibernateTemplate().getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(OnlineRecharge.class);

		criteria.add(Restrictions.eq("user.id", agent));
		criteria.add(Restrictions.eq("result", 0));
		criteria.addOrder(Order.desc("editetime"));
		int rowCount = ((Integer) criteria
				.setProjection(Projections.rowCount()).uniqueResult())
				.intValue();
		criteria.setProjection(null);
		int startIndex = pageSize * (pageNo - 1);
		criteria.setFirstResult(startIndex);
		criteria.setMaxResults(pageSize);
		List result = criteria.list();
		pager = new Pager(pageSize, pageNo, rowCount, result);

		session.close();

		return pager;
	}

}
